package portal.controller;

import beans.*;
import engine.BIEngine0_1.AlgorithmOperator;
import net.HttpRequest;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import portal.beans.Gpu;
import portal.beans.Node;
import portal.dao.ScheduleGpuDetailDao;
import portal.dao.ScheduleNodeDetailDao;
import portal.engine.JobOperator;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;

import java.io.*;
import java.util.ArrayList;
import java.util.List;


public class HostServlet extends BaseServlet {
    private static final long serialVersionUID = 2796970685901140947L;
    @Autowired
	 ScheduleGpuDetailDao scheduleGpuDetailDao;
    @Autowired
    ScheduleNodeDetailDao scheduleNodeDetailDao;
    private String token;
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String operateType = request.getParameter("operateType");
        /**
         * 获取token
         */
        HttpResult tokenResult = JobOperator.getToken(HttpConfig.userName, HttpConfig.passWord);
        if(tokenResult.isResult()) {
            this.token = tokenResult.getMessage();
        }
        switch (operateType) {
            case "getAllHostName":
                getAllHostName(request, response);
                break;
            case "getHost":
                getHostByHostName(request, response);
                break;
            /*case "setUpdateHostTime":
                setUpdateHostTime(request, response);
                break;*/
            default:
                break;
        }
    }

    /**
     * By 黄振  获取全部节点名称
     * @Param [request, response]
     * @return void
     **/
    protected void getAllHostName(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //基础设施资源监控，获取全部基础设施资源信息
        HttpResultList httpResultList = AlgorithmOperator.getJobBasicState(this.token);
        List<Object> hostList = new ArrayList<>();
        for (int i = 0; i < httpResultList.getDatas().size(); i++) {
            String hostName = ((BaseResourceState)httpResultList.getDatas().get(i)).getHostName();
            hostList.add(hostName);
        }
        JSONObject result = new JSONObject();
        result.put("hostName", JSONArray.fromObject(hostList));
        response.getWriter().print(result.toString());
    }

    /**
     * By 黄振 根据节点名称查询节点信息
     * @Param [request, response]
     * @return void
     **/
    protected void getHostByHostName(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String nodeName = request.getParameter("hostName");
        JSONObject nodeJson = new JSONObject();
        JSONObject httpResult = new JSONObject();
        //从静态表中取出的计算节点信息
        Node node = scheduleNodeDetailDao.getNodeByNodeName(nodeName);
        if(node==null){
            httpResult.put("result","fail");
            httpResult.put("message","查询失败");
            response.getWriter().write(httpResult.toString());
            return;
           }
        //ScheduleGpuDetailDao scheduleGpuDetailDao = new ScheduleGpuDetailDao();
        Gpu gpu = scheduleGpuDetailDao.getGpuById(node.getGpuId());
        nodeJson = JSONObject.fromObject(node);
        nodeJson.put("gpuDetail",gpu.getGpuDetail());
        nodeJson.put("gpuIdentify",gpu.getGpuIdentify());
        nodeJson.put("gpuVersion",gpu.getGpuVersion());

        /**
         * 访问接口取出的计算节点信息,hostList中存放的就是要查询的计算节点的信息
         */
        //获取token
        if(!HttpConfig.fake) {
            this.token = TokenValue.TOKEN.getTokenValue(HttpConfig.userName,HttpConfig.passWord);
            JSONObject result = JSONObject.fromObject(HttpRequest.sendGet(HttpConfig.getBaseResourceStateUrl,"token="+this.token));
            if(result.getString("result").contains("success")){
                JSONArray data = result.getJSONArray("data");
                for(int i=0;i<data.size();i++){
                    JSONObject oneData = data.getJSONObject(i);
                    if(nodeName.equals(oneData.getString("HOST_NAME"))){
                        nodeJson.put("ut",oneData.getString("ut"));
                        nodeJson.put("r15s",oneData.getString("r15s"));
                        nodeJson.put("r1m",oneData.getString("r1m"));
                        nodeJson.put("r15m",oneData.getString("r15m"));
                        nodeJson.put("pg",oneData.getString("pg"));
                        nodeJson.put("ls",oneData.getString("ls"));
                        nodeJson.put("it",oneData.getString("it"));
                        nodeJson.put("tmp",oneData.getString("tmp"));
                        nodeJson.put("swp",oneData.getString("swp"));
                        nodeJson.put("mem",oneData.getString("mem"));
                        nodeJson.put("type",oneData.getString("type"));
                    }
                }
            }
        }else{
            nodeJson.put("ut","ut");
            nodeJson.put("r15s","r15s");
            nodeJson.put("r1m","r1m");
            nodeJson.put("r15m","r15m");
            nodeJson.put("pg","pg");
            nodeJson.put("ls","ls");
            nodeJson.put("it","it");
            nodeJson.put("tmp","tmp");
            nodeJson.put("swp","swp");
            nodeJson.put("mem","mem");
            nodeJson.put("type","type");
        }
       // JSONObject httpResult = new JSONObject();
        if(node!=null){
            httpResult.put("result","success");
            httpResult.put("message",nodeJson);
        }
        response.getWriter().write(httpResult.toString());
    }

    /**
     * By黄振  设置定时更新资源的时间间隔，暂不使用
     * @Param [request, response]
     * @return void
     **/
    protected void setUpdateHostTime(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

//        String updateHostTime = request.getParameter("updateHostTime");
//        String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
//        path = path.split("target")[0];
//        Boolean bool = true;
//        Properties pro = new Properties();
//        try {
//            File file = new File(path+"src/main/resources/time.properties");
//            InputStream in = new FileInputStream(file);
//            pro.load(in);
//            in.close();
//
//            FileWriter outFile = new FileWriter (file);
//            outFile.write("");
//            outFile.flush();
//            pro.setProperty("updateHostTime",updateHostTime);
//            pro.store(outFile,null);
//            outFile.close();
//        } catch (IOException e) {
//            bool=false;
//            e.printStackTrace();
//        }
//        JSONObject result = new JSONObject();
//        result.put("message", bool);
//        response.getWriter().print(result.toString());
    }
}